package server;

import java.net.InetAddress;

import communication.ClientConnection;
import communication.Request;

/**
 * <h1>Class Session.</h1>
 * 
 * A session is created when an authenticated user signs on. It contains
 * the owner of the session, his/her IP address and the port in which s/he
 * is listening for responses from the server.
 * 
 * @author Tomas
 * @date March 4 2009
 */
public class Session {

	/**
	 * Owner of the session.
	 */
	protected Person owner = null;
	
	/**
	 * BuddyList for this person.
	 */
	protected BuddyList buddies = null;
	
	/**
	 * IP address of the user
	 */
	protected InetAddress ip = null;
	
	/**
	 * Port in which the user is listening for messages.
	 */
	protected int port = 0;
	
	/**
	 * Last time the user sent a message.
	 */
	protected long lastActivity;
	
	/**
	 * Initializes a new session for a user. It sets up the connection to the
	 * user.
	 */
	public Session(Person owner, InetAddress ip, int port, BuddyList buddies){
		
		this.owner = owner; 
		this.ip = ip;
		this.port = port;
		this.buddies = buddies;
		lastActivity = System.currentTimeMillis();
		
	}

	/**
	 * Obtains the owner of the connection
	 * 
	 * @return
	 */
	public Person getOwner() {
		
		return owner;
		
	}
	
	/**
	 * Sends a request/response to the user.
	 * 
	 * @param req
	 * 		Request to be sent
	 * @return
	 * 		Boolean value indicating if the transmission was successful or not.
	 */
	public boolean sendRequest(Request req){
		
		ClientConnection conn = null;
		
		try{
			conn = new ClientConnection(ip, port);
		}catch(Exception e){
			LogException.getInstance().logException(e);
			return false;
		}
		
		try{
			conn.writeRequest(req);
			conn.close();
		}catch(Exception e){
			LogException.getInstance().logException(e);
			return false;
		}
		
		return true;
	}
	
	/**
	 * Updates the last time of activity in the session.
	 */
	public void updateActivity(){
		
		lastActivity = System.currentTimeMillis();
		
	}
	
	/**
	 * Obtains the last time of activity in the session.
	 * 
	 * @return
	 * 		Last time of activity in the session.
	 */
	public long getLastActivity(){
	
		return lastActivity;
		
	}
	
	/**
	 * Obtains the buddy list for the owner of this session.
	 * 
	 * @return
	 * 		BuddyList for the person.
	 */
	public BuddyList getBuddyList(){
		
		return buddies;
		
	}
}
